package main

import (
	"fmt"
	"os"
	"os/exec"
	"strings"
)

var chPath string
var remoteUrl string
var useInput bool
var git string = "git"

type RefsContent struct {
	refs []string
}

// handle input args
func init() {
	switch os.Args[1] {
	case "-h":
		Usage()
		os.Exit(0)
	case "--help":
		Usage()
		os.Exit(0)
	}

	if len(os.Args) != 3 {
		return
	}
	useInput = true
	remoteUrl = os.Args[1]
	chPath = os.Args[2]
}

func main() {
	rc := &RefsContent{}
	if err := rc.BuildRefs(); err != nil {
		fmt.Println("ls-remote err: ", err)
		os.Exit(1)
	}

	rc.FetchRepo()
}

func (rc *RefsContent) BuildRefs() error {
	var cmd *exec.Cmd
	if useInput {
		cmd = exec.Command(git, "ls-remote", "--heads", remoteUrl)
	} else {
		cmd = exec.Command(git, "ls-remote", "--heads")
	}

	out, err := cmd.CombinedOutput()
	if err != nil {
		return err
	}

	result := strings.TrimSpace(string(out))
	refStr := strings.Split(result, "\n")[1:]

	for _, item := range refStr {
		ref := strings.Split(item, "\t")[1]
		if ref == "refs/heads/master" || ref == "HEAD" {
			continue
		}
		rc.refs = append(rc.refs, ref)
	}
	return nil
}

func (rc *RefsContent) FetchRepo() {
	for _, item := range rc.refs {
		var cmd *exec.Cmd
		refMap := item + ":" + item
		if useInput {
			cmd = exec.Command(git, "fetch", "--no-tags", remoteUrl, refMap)
			cmd.Dir = chPath
		} else {
			cmd = exec.Command(git, "fetch", "--no-tags", "origin", refMap)
		}
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr

		// fetch many branch, One or two errors are likely to occur, no need to block the process
		if err := cmd.Run(); err != nil {
			fmt.Println("fetch err: ", err)
		}
	}
}
